package se.energimyndigheten.lampguiden.conversiontable;

import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

import org.json.JSONException;

import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.SubPageActivity;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

import java.io.IOException;
import java.util.Map;

public class ConversionActivity extends SubPageActivity {

    private static final String TAG = ConversionActivity.class.getSimpleName();
    private static final String HELP_PATH = HTML_BASEPATH + "Help/sv_Conversion.html";

    private WebView mWebView;
    private Map<Integer, String> mTable;
    private Map<Integer, String> mTableR12;
    private Map<Integer, String> mTableR230;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.conversion_activity);

        try {
            mTable = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(
                    getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE),
                    "classic");
            mTableR12 = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(
                    getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE),
                    "halogen_gu53");
            mTableR230 = AssetsUtil.getConversionTableFromJson(AssetsUtil.getFileContents(
                    getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE),
                    "halogen_gu10");
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mWebView = (WebView) findViewById(R.id.webview);

        String html = "";
        // parse HTML and insert data at placeholder
        try {
            html = AssetsUtil.getFileContents(getAssets(), AssetsUtil.HTML_PATH_CONVERSION_TABLE);
            AssetsUtil.getParsedConversionTable(mTable);
            html = html.replace(AssetsUtil.HTML_PLACEHOLDER, AssetsUtil.getParsedConversionTable(mTable));
            html = html.replace(AssetsUtil.HTML_PLACEHOLDER_R12, AssetsUtil.getParsedConversionTable(mTableR12));
            html = html.replace(AssetsUtil.HTML_PLACEHOLDER_R230, AssetsUtil.getParsedConversionTable(mTableR230));
        } catch (IOException e) {
            Log.e(TAG, "IOException catched reading html.");
            e.printStackTrace();
        }
        mWebView.loadDataWithBaseURL(
                "file:///android_asset/" + AssetsUtil.HTML_PATH_CONVERSION_TABLE,
                html,
                "text/html",
                "UTF-8",
                null);
    }

    @Override
    protected void onResume() {
        mSelectedActivity = ACTIVITY_CONVERSION;
        super.showHelpActionItem(HELP_PATH);
        super.onResume();
    }
}
